package com.may.jwt.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.may.jwt.utils.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt拦截器
 * @author May
 * @date 2020/11/10 13:21
 */
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        // 获取请求头中的令牌
        String token = request.getHeader("token");
        try {
            // 验证令牌
            JWTUtil.verify(token);
            return true;
        } catch (SignatureVerificationException e) {
            map.put("status", false);
            map.put("msg", "token校验失败: 签名异常");
        }catch (TokenExpiredException e) {
            map.put("status", false);
            map.put("msg", "token校验失败: 已过期");
        }catch (AlgorithmMismatchException e) {
            map.put("status", false);
            map.put("msg", "token校验失败: 算法不匹配");
        }catch (Exception e) {
            map.put("status", false);
            map.put("msg", "token校验失败");
        }
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
